package gee

import (
	"net/http"
)

// Engine 结构体
type Engine struct {
	// router封装了string-handler
	router *router
}

// New Engine 构造函数
func New() *Engine {
	return &Engine{router: newRouter()}
}

// 给Engine的router添加路由map
func (engine *Engine) addRoute(method, pattern string, handler HandlerFunc) {
	engine.router.addRoute(method, pattern, handler)
}

func (engine *Engine) GET(pattern string, handlerFunc HandlerFunc) {
	engine.addRoute("GET", pattern, handlerFunc)
}

func (engine *Engine) POST(pattern string, handlerFunc HandlerFunc) {
	engine.addRoute("POST", pattern, handlerFunc)
}

func (engine *Engine) Run(addr string) (err error) {
	return http.ListenAndServe(addr, engine)
}

// Engine是Handler的实现，必须实现ServeHTTP方法
func (engine *Engine) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	// 将传入的req和resp封装成context传递到router
	c := newContext(writer, request)
	engine.router.handle(c)
}
